<?php
namespace app\front\logic;
use think\facade\Db;
use app\front\logic\OrderThirdPayLogLogic;

class EmailLogic{
	public static $init;
	static function init(){
		if (!isset(self::$init)) {//判断是否以前创建了当前类的实例
            $c = __CLASS__;//获取类名
            self::$init = new static;//如果没有创建，实例化当前类，这里实现类只实例化一次
        }
        return self::$init;//返回类的实例
	}

	function getList($lang='zh', $exchange_rate=1){
		$fields = "id,IFNULL(l.nums,0) as nums";
		if($lang=='zh'){
			$fields .= ",email_name";
		}else{
			$fields .= ",email_name_en as email_name";
		}
		$page_size = input('page_size', 10);
		$objs = Db::name('email')
				->alias('e')
				->field($fields)
				->join("(SELECT email_id, count(*) as nums FROM dg_email_list WHERE status=1 AND is_lock=0 AND has_buy=0 GROUP BY email_id) l","l.email_id=e.id","LEFT")
				->where('e.status', 1)
				->order('e.id asc')
				->paginate($page_size);
		$objs->render();
    	$list = $objs->toArray();
    	if($list && $list['data']){
    		$fieldst = "number";
    		if($lang=='en'){
    			$fieldst .= ", price / ".$exchange_rate." as price";
			}else{
				$fieldst .= ", price";
			}
			// echo $fieldst;
			foreach($list['data'] as $k=>$v){
				$list['data'][$k]['pack'] = Db::name('email_pack')
									->field($fieldst)
									->where('email_id', $v['id'])
									->where('status',1)
									->select()->toArray();
			}
		}
		return $list;
	}


	function buyEmail($lang='zh', $member_id=0, $amount=0){
		$email_id = input('email_id', 0);
		$number = input('number', 0);
		//参数不存在
		if(!$email_id){
			return ['code'=>141];
		}
		if(!$number){
			return ['code'=>140];
		}

		//查询邮箱类型的信息
		$info = $this->getType($email_id);
		if(!$info){
			return ['code'=>141];
		}
		//查询套餐和价格
		$pack = $this->getPrice($email_id, $number);
		if(!$pack){
			return ['code'=>141];
		}
		//查询邮箱剩余数量
		$counts = $this->getCounts($email_id);
		if($counts<$number){
			return ['code'=>142];
		}

		if($amount<$number*$pack['price']){
			return ['code'=>143];
		}
		//生成邮箱购买订单
		$dd = [];
		$dd['email_sn'] = CommonLogic::init()->createSn('order_email','email_sn',14,'number','EO');
		$dd['member_id'] = $member_id;
		$dd['email_id'] = $email_id;
		$dd['number'] = $number;
		$dd['pay_amount'] = $number * $pack['price'];
		$dd['status'] = 10;
		$dd['create_time'] = date('Y-m-d H:i:s');
		$dd['mdfkey'] = md5(time().".".$member_id);
		//新增邮箱订单
		$dd['id'] = $id = Db::name('order_email')->insertGetId($dd);
		if(!$id){
			return ['code'=>141];
		}
		//查询邮箱列表
		$list = Db::name('email_list')
				->where('email_id', $email_id)
				->where('status', 1)
				->where('is_lock', 0)
				->where('has_buy', 0)
				->orderRaw("rand()")
				->limit($number)
				->select();
		if(!$list){
			return ['code'=>141];
		}
		foreach($list as $k=>$v){
			//锁定
			$rs1 = Db::name('email_list')
					->where('id', $v['id'])
					->update(['is_lock'=>1,'order_email_id'=>$id]);
			if(!$rs1){
	    		return ['code'=>141];
			}
			//新增子订单
			$dd2 = [];
			$dd2['order_email_id'] = $id;
			$dd2['email_list_id'] = $v['id'];
			$dd2['email_account'] = $v['email_account'];
			$dd2['email_password'] = $v['email_password'];
			$dd2['price'] = $pack['price'];
			$dd2['create_time'] = date('Y-m-d H:i:s');
			$rs2 = Db::name('order_email_item')->insert($dd2);
			if(!$rs2){
	    		return ['code'=>141];
			}
		}
		//日志
		$ldata = [];
		$ldata['out_order_id'] = $id;
		$ldata['order_type'] = 30;
		$ldata['payment_type'] = 40;
		$ldata['member_id'] = $dd['member_id'];
		// $ldata['trade_number'] = $dd['email_sn']."_".rand(100,999);
		$ldata['pay_amount'] = $dd['pay_amount'];
		$ldata['payment_status'] = 10;
		$ldata['begin_time'] = date('Y-m-d H:i:s');
		$lid = OrderThirdPayLogLogic::init()->add($ldata);
		if(!$lid){
    		return ['code'=>141];
		}
		return ['code'=>0,'data'=>$dd];
	}
	//获取邮箱类型信息
	function getType($email_id=0){
		$info = Db::name('email')
					->field('id')
					->where('id', $email_id)
					->where('status', 1)
					->find();
		return $info;
	}
	//查询价格
	function getPrice($email_id=0, $number=1){
		$info = Db::name('email_pack')
					->field('id,email_id,number,price')
					->where('email_id', $email_id)
					->where('status', 1)
					->where('number', '<=', $number)
					->order('number desc')
					->find();
		return $info;
	}
	//查询数量
	function getCounts($email_id=0){
		$counts = Db::name('email_list')
					->where('email_id', $email_id)
					->where('status', 1)
					->where('is_lock', 0)
					->where('has_buy', 0)
					->count('id');
		return $counts;
	}

	//查询购买的邮箱
	function showEmailList($mdfkey=''){
		$lists = Db::name('order_email')
					->field('email_account,email_password')
					->alias('oe')
					->join('order_email_item oei','oei.order_email_id=oe.id')
					->where('oe.mdfkey', $mdfkey)
					->select();
		return $lists;
	}

	//获取购买的邮箱订单列表
	function getOrderList($lang='zh', $member_id=0, $exchange_rate){
		$fields = "oe.id,oe.email_sn,oe.member_id,round(pay_amount / $exchange_rate, 2) as pay_amount,number,mdfkey,oe.status,oe.create_time,pay_time";
		if($lang=='zh'){
			$fields .= ',e.email_name';
		}else{
			$fields .= ',e.email_name_en as email_name';
		}
		// echo $member_id;
		$page_size = input('page_size', 10);
		$start_time = input('start_time','');
		$end_time = input('end_time','');
		$start_time && $start_time = $start_time." 00:00:00";
		$end_time && $end_time = $end_time." 23:59:59";
		$obj = Db::name('order_email')
					->alias('oe')
					->field($fields)
					->join('email e','e.id=oe.email_id','left')
					->where('oe.member_id', $member_id);
		if($start_time){
			$obj->where('oe.create_time','>=', $start_time);
		}

		if($end_time){
			$obj->where('oe.create_time','<=', $end_time);
		}

		$list = $obj->order('oe.id desc')
					->paginate($page_size);
		return $list;
	}


	//文件流
	function getFileStream($mdfkey=''){
		$info = Db::name('order_email')
				->field('id')
				->where('mdfkey', $mdfkey)
				->find();

		// print_r($info);
		$path = root_path().'public/emailfile/'.$info['id'];

		

		if(!file_exists($path)){
			mk_dir($path);
		}
		$file = $path.'/'.$mdfkey.'.txt';
		// $url_file = "http://www.fwdg.com/emailfile/".$info['id'].'/'.$mdfkey.'.txt';
		if(!file_exists($file)){
			$lists = Db::name('order_email')
					->field('email_account,email_password')
					->alias('oe')
					->join('order_email_item oei','oei.order_email_id=oe.id')
					->where('oe.mdfkey', $mdfkey)
					->select();
			$strings = "";
			if($lists){
				foreach($lists as $v){
					$strings .= $v['email_account'].'------'.$v['email_password']."\n";
				}
			}
			$myfile = fopen($file, "w") or die("Unable to open file!");
			fwrite($myfile, $strings);
			fclose($myfile);
		}


	    $outFileName = $mdfkey.'.txt';
	    // 设置下载头信息
	    header( 'Content-Type:text/html;charset=utf-8 ');
	    header ( "Content-Disposition: attachment; filename=".$outFileName );

	    // 文件流输出到浏览器
	    readfile($file);
	    // 删除文件
	    // @unlink($file); 

	    
	}
	

	function StrToBin($str){
        //1.列出每个字符
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        //2.unpack字符
        foreach($arr as &$v){
            $temp = unpack('H*', $v);
            $v = base_convert($temp[1], 16, 2);
            unset($temp);
        }

        return join(' ',$arr);
    }

}